package com.mx.adapt.picker

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import androidx.viewbinding.ViewBinding
import com.mx.adapt.MXBaseSimpleAdapt
import com.mx.adapt.MXBaseViewHolder
import com.mx.adapt.databinding.LayoutMxPickerEmptyBinding

internal class MXScrollPickerAdapt(private val scrollView: MXScrollPickerView) :
    MXBaseSimpleAdapt<Any>() {
    var adapt: MXBaseSimpleAdapt<*>? = null
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MXBaseViewHolder {
        if (viewType != Int.MAX_VALUE / 2) {
            adapt?.onCreateViewHolder(parent, viewType)?.let {
                return it
            }
        }
        return super.onCreateViewHolder(parent, viewType)
    }

    override fun onBindViewHolder(holder: MXBaseViewHolder, position: Int) {
        if (position >= scrollView.itemOffset && position < (itemCount - scrollView.itemOffset)) {
            adapt?.onBindViewHolder(holder, position - scrollView.itemOffset)
        }
        val lp = (holder.binding.root.layoutParams as RecyclerView.LayoutParams)
        lp.height = scrollView.itemHeight
        holder.binding.root.layoutParams = lp
        holder.itemView.setOnClickListener {
            itemClickCall?.invoke(position, Any())
        }
    }

    override fun getItemViewType(position: Int): Int {
        val maxCount = itemCount
        if (position < scrollView.itemOffset || position >= (maxCount - scrollView.itemOffset)) {
            return Int.MAX_VALUE / 2
        }

        return super.getItemViewType(position)
    }

    override fun getItemCount(): Int {
        return (adapt?.itemCount ?: 0) + scrollView.itemOffset * 2
    }

    override fun createItem(
        inflater: LayoutInflater,
        parent: ViewGroup,
        viewType: Int
    ): ViewBinding {
        return LayoutMxPickerEmptyBinding.inflate(inflater, parent, false)
    }
}